package com.uls.web.controller.czj;

import java.security.acl.LastOwnerException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.uls.common.core.domain.entity.SysUser;
import com.uls.common.utils.SecurityUtils;
import com.uls.framework.config.MinioProp;
import com.uls.framework.utils.MinioUtils;
import com.uls.system.service.ISysUserService;
import com.uls.web.controller.system.SysUserController;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.uls.common.annotation.Log;
import com.uls.common.core.controller.BaseController;
import com.uls.common.core.domain.AjaxResult;
import com.uls.common.enums.BusinessType;
import com.uls.czj.domain.CzjStudents;
import com.uls.czj.service.ICzjStudentsService;
import com.uls.common.utils.poi.ExcelUtil;
import com.uls.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;



/**
 * 学生信息Controller
 * 
 * @author czj
 * @date 2024-10-30
 */
@RestController
@RequestMapping("/czj/students")
public class CzjStudentsController extends BaseController
{
    @Autowired
    private ICzjStudentsService czjStudentsService;


    @Autowired
    private MinioUtils minioUtils;


    @Autowired
    private MinioProp minioProp;

    @Autowired
    private ISysUserService userService;

    /**
     * 查询学生信息列表
     */
    @PreAuthorize("@ss.hasPermi('czj:students:list')")
    @GetMapping("/list")
    public TableDataInfo list(CzjStudents czjStudents)
    {
        startPage();
        List<CzjStudents> list = czjStudentsService.selectCzjStudentsList(czjStudents);

        List<CzjStudents> list1 = new ArrayList<>();
        for (CzjStudents czjStudents1 : list){
            if (czjStudents1.getDeleteBy()!=null){
                continue;
            }
            list1.add(czjStudents1);
        }
        return getDataTable(list1);
    }

    /**
     * 导出学生信息列表
     */
    @PreAuthorize("@ss.hasPermi('czj:students:export')")
    @Log(title = "学生信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CzjStudents czjStudents)
    {
        List<CzjStudents> list = czjStudentsService.selectCzjStudentsList(czjStudents);
        ExcelUtil<CzjStudents> util = new ExcelUtil<CzjStudents>(CzjStudents.class);
        util.exportExcel(response, list, "学生信息数据");
    }

    /**
     * 获取学生信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('czj:students:query')")
    @GetMapping(value = "/{studentId}")
    public AjaxResult getInfo(@PathVariable("studentId") Long studentId)
    {
        return success(czjStudentsService.selectCzjStudentsByStudentId(studentId));
    }

    /**
     * 新增学生信息
     */
    @PreAuthorize("@ss.hasPermi('czj:students:add')")
    @Log(title = "学生信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CzjStudents czjStudents)
    {
        String studentId = null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String temp=dateFormat.format(czjStudents.getEnrollmentDate());
        System.out.println(temp);

        CzjStudents students = new CzjStudents();
        students.setMajor(czjStudents.getMajor());
        students.setEnrollmentDate(czjStudents.getEnrollmentDate());
        List<CzjStudents> studentsList= czjStudentsService.selectCzjStudentsList(students);
        Long i=101l;
        if (studentsList.size()!=0){
            for (CzjStudents students1:studentsList){
                Long j =  students1.getStudentNumber();
                if (j>i){
                    i=j;
                }
            }
            Long x=i/100*100+40;
            if (i>=x){
                i=x+61;
            }else {
                i++;
            }
        }
        String num = String.valueOf(i);


        studentId=temp.substring(2,4)+czjStudents.getMajor()+num.substring(num.length()-3,num.length());
        System.out.println(studentId);
        czjStudents.setStudentNumber(Long.parseLong(studentId));


        czjStudents.setCreatedBy(this.getUsername());
        czjStudents.setCreatedTime(new Date());

        SysUser sysUser = new SysUser();
        Long id[]={100l};
        sysUser.setRoleIds(id);
        sysUser.setAvatar(czjStudents.getPhoto());
        sysUser.setUserName(String.valueOf(czjStudents.getStudentNumber()));
        sysUser.setNickName(czjStudents.getName());
        sysUser.setPassword("admin123");
        sysUser.setCreateBy(this.getUsername());
        sysUser.setCreateTime(new Date());
        sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
        userService.insertUser(sysUser);
        return toAjax(czjStudentsService.insertCzjStudents(czjStudents));
    }

    /**
     * 修改学生信息
     */
    @PreAuthorize("@ss.hasPermi('czj:students:edit')")
    @Log(title = "学生信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CzjStudents czjStudents)
    {
        czjStudents.setUpdatedBy(this.getUsername());
        czjStudents.setUpdatedTime(new Date());
        SysUser user = userService.selectUserByUserName(String.valueOf(czjStudents.getStudentNumber()));
        user.setUpdateBy(this.getUsername());
        user.setUpdateTime(new Date());
        user.setNickName(czjStudents.getName());
        user.setAvatar(czjStudents.getPhoto());
        userService.updateUser(user);
        return toAjax(czjStudentsService.updateCzjStudents(czjStudents));
    }

    /**
     * 删除学生信息
     */
    @PreAuthorize("@ss.hasPermi('czj:students:remove')")
    @Log(title = "学生信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{studentIds}")
    public AjaxResult remove(@PathVariable Long[] studentIds)
    {
        CzjStudents czjStudents = new CzjStudents();
        for (Long id :studentIds){
            czjStudents= czjStudentsService.selectCzjStudentsByStudentId(id);
            czjStudents.setDeleteBy(this.getUsername());
            czjStudents.setDeleteTime(new Date());
            SysUser sysUser = userService.selectUserByUserName(String.valueOf(czjStudents.getStudentNumber()));


            czjStudentsService.updateCzjStudents(czjStudents);
            userService.deleteUserById(sysUser.getUserId());
        }

        return toAjax(czjStudentsService.updateCzjStudents(czjStudents));
    }


    /**
     * 上传头像图片
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public String upload(@RequestParam(name = "file", required = false) MultipartFile file, HttpServletRequest request) {
        JSONObject res = null;
        try {
            res = minioUtils.uploadFile(file, minioProp.getBucket());
        } catch (Exception e) {
            e.printStackTrace();
            res.put("code", 0);
            res.put("msg", "上传失败");
        }
        return res.toJSONString();
    }
}
